module MC.Call {
    export class MsgList {
        public constructor() {
        }

        private uid: string = '';

        public getlist() {
            MC.Call.Jiguang((uid: string, obj: any) => {
                this.uid = uid;
                this.loadMsg();
            });
            /* MC.api('getmsglist', {}, (json: any) => {
                this.upList(json);
            }); */
        }

        private loadMsg() {
            this.loadlixianxiaoxi(() => {
                JIM.getConversation().onSuccess((data: any) => {
                    this.loadUserPicList(data.conversations);

                });
            });
        }

        /**
         * 加载用户的头像,并显示出来
         * */
        private loadUserPicList(conversations: any) {
            let nlist = [];
            for (let i = 0; i < conversations.length; i++) {
                nlist.push(conversations[i].username);
            }
            let namelist = nlist.join(",");
            MC.api('getuserListhead', {namelist: namelist}, (data: any) => {
                /// console.log(data);
                for (let i = 0; i < conversations.length; i++) {
                    conversations[i].avatar = data[conversations[i].username] || '';
                }
                //   console.log(conversations);
                this.upList(conversations);
                this.onMsgReceive();
            });
            //console.log(conversations);
        }

        /**
         * 开始监听实时消息
         * */
        private onMsgReceive() {
            JIM.onMsgReceive(function (data: any) {
                console.log(data);
                MC.Call.newmsgAudio();
                for (let i = 0; i < data.messages.length; i++) {
                    let one = data.messages[i];
                    console.log(one, one.from_username);
                    let li = $('[from_username=' + one.from_username + ']');
                    let a = li.find('.headDiv .count');
                    let count: any = a.text();
                    if (count == '') {
                        count = 0;
                    }
                    count = parseInt(count);
                    a.text(count + 1);
                    if (one.content.msg_type == 'image') {
                        li.find('.LastText').text('图片');
                    } else if (one.content.msg_type == 'text') {
                        li.find('.LastText').text(one.content.msg_body.text);
                    } else {
                        li.find('.LastText').text('未知类型消息');
                    }

                    a.show();
                }
                // data.messages[]
                // data.messages[].ctime_ms
                // data.messages[].msg_type 会话类型
                // data.messages[].msg_id
                // data.messages[].from_appey 单聊有效
                // data.messages[].from_username 单聊有效
                // data.messages[].from_gid 群聊有效
                // data.messages[].need_receipt
                // data.messages[].content
                // data.messages[].custom_notification.enabled
                // data.messages[].custom_notification.title
                // data.messages[].custom_notification.alert
                // data.messages[].custom_notification.at_prefix
            });
        }

        /*
        private upList(list: any) {
            $('.load').hide();
            for (let i = list.length - 1; i >= 0; i--) {
                let li = list[i];
                if (MC.Call.isAdmin(li.name)) {
                    continue;
                }
                if (li.unread_msg_count == 0) {
                    li.unread_msg_count = '';
                } else {
                    li.unread_msg_count = `<span class="count">` + li.unread_msg_count + `</span>`;
                }
                let html = `<a href="jobWin.html?uid=` + MC.API.jiguangIdToSytem(li.username) + `" 
					class="aui-six-list-item">
						<div class="aui-flex b-line">
							<div class="aui-flex-box">								
								<h3>` + li.unread_msg_count + ` ` + li.nickName + `</h3>								
								<div class="clearfix">
								<p>` + MC.API.timeTostr(li.mtime) + `</p>
									</div>
								</div>
							<div class="qujiaoliuDiv" ><p>去交流</p>
						</div>
					</div>
				</a>`;
                $('#msglist').append(html);
            }
        }*/


        private upList(list: any) {
            $('.load').hide();
            for (let i = list.length - 1; i >= 0; i--) {
                let li = list[i];
                if (MC.Call.isAdmin(li.name)) {
                    continue;
                }
                if (li.unread_msg_count == 0) {
                    li.unread_msg_count = `<span class="count none">0</span>`;
                } else {
                    if (li.unread_msg_count > 99) {
                        li.unread_msg_count = 99;
                    }
                    li.unread_msg_count = `<span class="count">` + li.unread_msg_count + `</span>`;
                }
                let html = $(`<a from_username="` + li.username + `" href="jobWin.html?uid=` + MC.API.jiguangIdToSytem(li.username) + `"
					class="aui-six-list-item">
						<div class="b-line clearfix">
							<div class="headDiv">
							    <img src="` + li.avatar + `" class="headpic"/>
							    ` + li.unread_msg_count + `
                            </div>
                            <div class="context">
                                <div class="nametimeDiv">
                                    <p class="name">` + li.nickName + `</p>
                                    <span class="time">` + MC.API.timeTostr(li.mtime) + `</span>
                                </div>
                                <p class="LastText"></p>
                            </div>
						</div>
					</div>
				</a>`);
                //` + this.getLastText(li.name) + `
                html.find('.LastText').text(this.getLastText(li.name));
                $('#msglist').append(html);
            }
        }


        /**
         * 加载离线消息,补全最后的消息内容
         * */
        private loadlixianxiaoxi(fun: Function) {
            let m = JIM.onSyncConversation((data: any) => {
                //  console.log(data);
                this.SyncConversation = data;
                fun();
            });
            // console.log(m);
        }

        /**
         * 离线的消息
         * */
        private SyncConversation: any = [];

        /**
         * 获取指定用户的最后一条信息的内容
         * */
        private getLastText(name: string) {
            let one = null;
            for (let i = 0; i < this.SyncConversation.length; i++) {
                let li = this.SyncConversation[i];
                if (li.from_username == name) {
                    one = li.msgs[li.msgs.length - 1];
                }
            }
            if (one && one.content) {
                let content = one.content;
                if (content.msg_type == 'image') {
                    return '图片';
                } else if (content.msg_type == 'text') {
                    return content.msg_body.text;
                }
            }
            return '未知类型';
        }


    }


    export function getmsgUnreadCount() {
        //console.log('getmsgUnreadCount()');
       /* if (!$('#toMessagePage')[0]) {
            return;
        }*/
       if($('.loadJiguangMsg,.noloadJiguangMsg')[0]){
           return;
       }
        let count: any = MC.Cache.getObj('getmsgUnreadCount');   /// localStorage.getItem('getmsgUnreadCount');
        let adminCount: any = MC.Cache.getObj('getmsgUnreadCountadmin');   ///  localStorage.getItem('getmsgUnreadCountadmin');
        if (adminCount) {
            $('#locateMessageTop #sys').text(adminCount);
        }
        if (count) {
            $('#business').text(count);
        }

        if ((count && count > 0) || (adminCount && adminCount > 0)) {
            let msgon = `<i class="msgOn"></i>`;
            $('#toMessagePage').append(msgon);
            $('#toMessagePage .msgOn').show();
        }

        let uid = '';
        MC.Call.Jiguang((_uid: string, obj: any) => {
            uid = _uid;
            JIM.getConversation().onSuccess((data: any) => {
                //	console.log(data.conversations);
                let list = data.conversations;
                let count: any = 0;
                let adminCount: any = 0;
                for (let i = 0; i < list.length; i++) {
                    let one = list[i];
                    if (MC.Call.isAdmin(one.username)) {
                        adminCount += one.unread_msg_count;
                    } else {
                        count += one.unread_msg_count;
                    }
                }
                // localStorage.setItem('getmsgUnreadCount', count);
                /// localStorage.setItem('getmsgUnreadCountadmin', adminCount);
                MC.Cache.setObj('getmsgUnreadCount', count);
                MC.Cache.setObj('getmsgUnreadCountadmin', adminCount);
                $('#business').text(count);
                $('#locateMessageTop #sys').text(adminCount);
                if (count > 0 || adminCount > 0) {
                    if (!$('#toMessagePage .msgOn')[0]) {
                        let msgon = `<i class="msgOn"></i>`;
                        $('#toMessagePage').append(msgon);
                    }
                    $('#toMessagePage .msgOn').show();
                } else {
                    $('#toMessagePage .msgOn').hide();
                }

                JIM.onMsgReceive(function (data: any) {
                        console.log(data);
                        MC.Call.newmsgAudio();
                        let messages = data.messages;
                        for (let i = 0; i < messages.length; i++) {
                            let one = messages[i];
                            if (MC.Call.isAdmin(one.from_username)) {
                                adminCount += 1;
                            } else {
                                count += 1;
                            }
                        }
                        MC.Cache.setObj('getmsgUnreadCount', count);
                        MC.Cache.setObj('getmsgUnreadCountadmin', adminCount);
                        $('#business').text(count);
                        $('#locateMessageTop #sys').text(adminCount);
                        if (count > 0 || adminCount > 0) {
                            if (!$('#toMessagePage .msgOn')[0]) {
                                let msgon = `<i class="msgOn"></i>`;
                                $('#toMessagePage').append(msgon);
                            }
                            $('#toMessagePage .msgOn').show();
                        } else {
                            $('#toMessagePage .msgOn').hide();
                        }


                    }
                );


            });
        });


    }

    $(() => {
        //	getmsgUnreadCount();
    });
}